package com.tz.water.controller.common;

import com.tz.water.bean.Device;
import com.tz.water.mapper.DeviceMapperImpl;
import com.tz.water.utils.SpringUtil;
import lombok.SneakyThrows;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 易水●墨龙吟
 * @Description
 * @create 2019-04-14 23:21
 */
public class ServerConfig extends Thread {

    private Socket socket;

    public ServerConfig(Socket socket) {
        this.socket = socket;
    }
    // 获取spring容器管理的类，可以获取到sevrice的类
    private DeviceMapperImpl service = SpringUtil.getBean(DeviceMapperImpl.class);

    private Device handle(InputStream inputStream) throws Exception {
        byte[] bytes = new byte[1024];
        int len = inputStream.read(bytes);
        if (len != -1) {
            StringBuffer request = new StringBuffer();
            request.append(new String(bytes, 0, len, "UTF-8"));
            System.out.println("接受的数据: " + request);
            System.out.println("from client ... " + request + "当前线程" + Thread.currentThread().getName());
            String req = request.toString();
            System.out.println("from client ... " + req);

            String data[] = req.split(":");
            if(data.length <3)
                return null;
            Device device = new Device();
            device.setIsheating(Integer.parseInt(replaceBlank(data[1])) == 1);
            device.setTemp(Double.parseDouble(replaceBlank(data[0])));
            device.setIsoutingwater(Integer.parseInt(replaceBlank(data[2])) == 1);
            return device;
        } else {
            socket.close();
            throw new Exception("data leng == -1");
        }
    }
    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
    @SneakyThrows
    @Override
    public void run() {
        BufferedWriter writer = null;
        try {
            // 设置连接超时9秒

            socket.setSoTimeout(0);
            System.out.println("客户 - " + socket.getRemoteSocketAddress() + " -> 机连接成功");
            while (true){
                InputStream inputStream = socket.getInputStream();
                writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                try {
                    Device device  = handle(inputStream);
                    if(device != null){
                        device.setIsoutingwater(null);
                        service.updatestate(device);
                    }
                    writer.write(service.getlast().getIsoutingwater() ? "outwater:1": "outwater:0");
                    writer.newLine();
                    writer.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (SocketException socketException) {
            writer.close();
            socketException.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();
        } finally {
//            try {
//                writer.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
        }
    }
}